var express = require('express');
var router = express.Router();
var db = require('../../mysqldb');
module.exports = function (app) {
    app.use('/admin/addlist', router);
};

//添加二级模块
router.post('/addlist', async (req, res, next) => {
      db(`INSERT INTO AddList VALUES (null,'${req.body.Name}',${req.body.Type},${req.body.FrId},'${new Date()}',${req.body.IsIndex},${req.body.IsDisplay},${req.body.Sort},${req.body.Shows})`,(err,rows)=>{
          if(err){
              res.send({res:false})
          }
          res.send({ret:true})
      });
})

// router.get('/aaa',(req,res,next)=>{
//     console.log(req)
//     db(`select * from AddList where FrId='${req.query.id}'`,(err,rows)=>{
//        res.send(rows)
//     })
// })

//修改二级模块
router.post('/update',(req, res, next) => {
    db(`UPDATE AddList SET Name='${req.body.Name}',Type=${req.body.Type},FrId=${req.body.FrId},IsIndex=${req.body.IsIndex},IsDisplay=${req.body.IsDisplay},Sort=${req.body.Sort},Shows=${req.body.Shows} where id=${req.body.id}`,(err,rows)=>{
        if(err){
            console.log(err)
            res.send({res:false})
            return
        }
        res.send({ret:true})
        
    });
})

//展示全部二级模块
router.post('/show',  (req, res, next) => { 
    db('select * from AddList order by Sort desc',(err,rows)=>{
      if(err){
        res.send({ret:false})
      }
      var newdata=[[],[],[],[],[],[],[]];
      rows.forEach((item,index)=>{
        let id = ""
          if(item.Type == 2){
            newdata[item.FrId-7].push({
                a:item,
                b:[]
            })
            // id = item.id
            // db(`select * from AddList where FrId=${id}`,async(err,rows)=>{
            //     newdata[item.FrId-7][newdata[item.FrId-7].length-1].b = rows
            //     console.log(newdata[item.FrId-7][newdata[item.FrId-7].length-1].b)
            // })
          }
      })
      newdata.forEach((item1,index1)=>{
            item1.forEach((item2,index2)=>{
                rows.forEach((item,index)=>{
                    if(item.Type==3){
                        if(item.FrId == item2.a.id){
                            newdata[index1][index2].b.push(item)
                        }
                    }
                })
            })
      })
      if(req.body.ftype){
        res.send({ret:true,data:newdata[req.body.ftype]})
      }else{
        res.send({ret:true,data:newdata})
      }
      
    });
})
router.post('/showone',(req,res,next)=>{
    db(`select * from AddList where id='${req.body.id}'`,(err,rows)=>{
        if(err){
            res.send({res:false,data:err})
        }
        res.send({ret:true,data:rows[0]})
    })
})

//删除二级模块
router.post('/del', async (req, res, next) => {
    db(`DELETE  from AddList where id='${req.body.id}'`,(err,rows)=>{
      if(err){
          res.send({ret:false})
      }
      res.send({ret:true})
    });
})
